package cn.sjx.auth.service.impl;

import cn.sjx.auth.service.LoginService;
import cn.sjx.basic.utils.BasicMap;
import cn.sjx.dto.LoginDTO;
import cn.sjx.org.domain.Employee;
import cn.sjx.org.mapper.EmployeeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    EmployeeMapper employeeMapper;

    @Override
    public Map<String, Object> login(LoginDTO loginDTO) {

        String username = loginDTO.getUsername();
        String password = loginDTO.getPassword();
        //1. 检验参数是否为空
        if (username.equals("") || password.equals("")){
            throw new RuntimeException("用户名或密码不正确");
        }
        //2. 根据用户名获取对象
        Employee employee = employeeMapper.loadByUsername(username);

        //3. 判断员工是否存在
        if (Objects.isNull(employee)){
            //3.1 如果不存在，提示
            throw new RuntimeException("用户名或密码不正确");
        }

        //3.2 如果存在，则比对密码
        if(!password.equals(employee.getPassword())){
            //3.3 密码不正确，提示
            throw new RuntimeException("用户名或密码不正确");
        }

        //4. 生成通过uuid生成唯一token
        String token = UUID.randomUUID().toString();
        //5. 以该token为键，员工对象为值放入全局map中
        BasicMap.loginMap.put(token, employee);
        //6. 返回
        //6.1 map.put("token",token)
        Map<String,Object> map = new HashMap<>();
        map.put("token", token);
        //6.2 map.put("user",employee),返回前要将密码置空
        employee.setPassword("");
        map.put("loginUser", employee);

        return map;
    }
}
